package com.cty.HashTable;

/*
 *
 * 哈希表中的每个员工链表
 *
 * */
public class EmpLinkedList {
    //头节点就是第一个数据
    Emp head = null;

    //添加方法(不按顺序插入)
    public void add(Emp emp) {
        //头节点为空
        if (head == null) {
            head = emp;
            return;
        }
        //插入数据比头节点id小
        if (head.id > emp.id) {
            Emp temp = head;
            head = emp;
            head.next = temp;
            return;
        }
        //寻找合适的查找位置
        Emp temp = head;
        while (true) {
            if (temp.next == null) {
                temp.next = emp;
                return;
            }
            if (temp.next.id > emp.id) {
                emp.next = temp.next;
                temp.next = emp;
                return;
            }
            temp = temp.next;
        }
    }

    //遍历链表的方法
    public void list(int i) {
        if (head == null) {
            System.out.println("第" + (i + 1) + "个链表为空");
            return;
        }
        Emp temp = head;
        System.out.print("第" + (i+1) +"条链表");
        while (true) {
            System.out.printf("=> id:%d 员工姓名：%s\t", temp.id, temp.name);
            if (temp.next == null) {
                break;
            }
            temp = temp.next;
        }
        System.out.println();
    }

    //寻找方法
    public Emp find(int id) {
        if (head == null) {
            return null;
        }
        Emp temp = head;
        while (true) {
            if (temp.id == id) {
                return temp;
            }
            if (temp.next == null) {
                return null;
            }
            temp = temp.next;
        }
    }

    //删除方法
    public void delete(int id) {
        if (head == null) {
            System.out.println("没有找到id为"+id+"的员工");
            System.out.println();
            return;
        }
        if (head.id == id) {
            head = head.next;
            System.out.println("删除成功！");
            return;
        }
        Emp temp = head;
        while (true) {
            if (temp.next == null) {
                System.out.println("没有找到id为"+id+"的员工");
                return;
            }
            if (temp.next.id == id) {
                break;
            }
            temp = temp.next;
        }
        if (temp.next.next != null) {
            temp.next = temp.next.next;
        } else {
            temp.next = null;
        }
        System.out.println("删除成功！");
    }
}
